package com.sangeng.handler;

import com.alibaba.fastjson.JSON;
import com.sangeng.domain.ResponseResult;
import com.sangeng.utils.WebUtils;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author LENOVO
 * @version 1.0
 * @date 2025/6/19 21:56
 * 授权过程中出现的异常会被封装成AccessDeniedException然后调用AccessDeniedHandler对
 * 象的方法去进行异常处理。
 */

@Component
public class AccessDeniedHandlerImpl implements AccessDeniedHandler {
    /**
     * 授权过程中出现的异常会被封装成AccessDeniedException然后调用AccessDeniedHandler对象
     * 的方法去进行异常处理。
     * @param httpServletRequest 请求
     * @param httpServletResponse 响应
     * @param e 异常
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AccessDeniedException e) throws IOException, ServletException {
        // 返回认证失败信息
        ResponseResult result = new ResponseResult(HttpStatus.FORBIDDEN.value(), "授权失败请重新登录");
        String json = JSON.toJSONString(result);
        //异常处理,使用工具类返回给前端
        WebUtils.renderString(httpServletResponse , json);
    }
}